package org.honeyweb.gsoc.dao.hibernate3;

import java.util.ArrayList;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.honeyweb.gsoc.dao.OrganizationsDao;
import org.honeyweb.gsoc.model.Organizations;
import org.honeyweb.gsoc.model.Users;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class OrganizationsDaoImpl extends HibernateDaoSupport implements OrganizationsDao {
	
	@PersistenceContext
	private EntityManager entityManager;
	
	/**
	 * {@inheritDoc}
	 */
	public Organizations getOrganization(Users user){
		if (null == user ) {
			throw new IllegalArgumentException("user is mandatory. Null value is forbidden.");
		}
		try {
			logger.info("get Organization with login: "+ user.getLogin());
			Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
			// create a new criteria
			Criteria crit = session.createCriteria(Organizations.class);
			crit.add(Restrictions.eq("id", user.getOrganizationsId()));
			
			Organizations organization = (Organizations)crit.uniqueResult();
			return organization;
		}
		catch(DataAccessException e) {
			// Critical errors : database unreachable, etc.
			logger.error("Exception - DataAccessException occurs : "+e.getMessage()
					+" on complete getOrganizations().");
			return null;
		}
	}
	
	/**
	 * {@inheritDoc}
	 */
	public Organizations getOrganizationByAdminId(int adminId){
		if (0 == adminId ) {
			throw new IllegalArgumentException("adminId is mandatory. Null value is forbidden.");
		}
		try {
			logger.info("get Organization with AdminId: "+ adminId);
			Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
			// create a new criteria
			Criteria crit = session.createCriteria(Organizations.class);
			crit.add(Restrictions.eq("adminId", adminId));
			
			Organizations organization = (Organizations)crit.uniqueResult();
			return organization;
		}
		catch(DataAccessException e) {
			// Critical errors : database unreachable, etc.
			logger.error("Exception - DataAccessException occurs : "+e.getMessage()
					+" on complete getOrganizations().");
			return null;
		}
	}
	
	/**
	 * {@inheritDoc}
	 */
	public ArrayList<Organizations> getListOrganizations(){
		try {
			Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
			// create a new criteria
			Criteria crit = session.createCriteria(Organizations.class);
			
			ArrayList<Organizations> listOrganization = (ArrayList<Organizations>)crit.list();
			return listOrganization;
		}
		catch(DataAccessException e) {
			// Critical errors : database unreachable, etc.
			logger.error("Exception - DataAccessException occurs : "+e.getMessage()
					+" on complete getOrganizations().");
			return null;
		}
	}
	
	/**
	 * {@inheritDoc}
	 */
	public void addOrganization(Organizations organization){
		if (null == organization) {
			throw new IllegalArgumentException("An organization has to be specified");
		}	
		try {
			Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
			session.save(organization);
		}
		catch(DataAccessException e) {
			// Critical errors : database unreachable, etc.
			logger.error("Exception - DataAccessException occurs : "+e.getMessage()
					+" on complete checkLogin().");
		}
	}
	
    public void addOrganizationsHoneypotsId(int organizationId, int honeypotsId){
		if (0 == organizationId || 0 == honeypotsId) {
			throw new IllegalArgumentException("An organizationId and a honeypotsId have to be specified");
		}	
		try {
			logger.debug("organizationId: " + organizationId + "honeypotsId: " + honeypotsId);
			Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
			Organizations organization = (Organizations) session.load(Organizations.class, new Integer(organizationId));
			
			//We add the HoneypotId to the honeypots list of our current Organization
			String listHoneypotsId = organization.getHoneypotsId();
			logger.debug("listHoneypotsId:" + listHoneypotsId);
			if (listHoneypotsId == null ){
				listHoneypotsId = String.valueOf(honeypotsId);
			}
			else{
				listHoneypotsId = listHoneypotsId.concat(","+String.valueOf(honeypotsId));
			}
			logger.debug("listHoneypotsId after concat:" + listHoneypotsId);
			organization.setHoneypotsId(listHoneypotsId); 
			session.update(organization);
			session.flush();
			session.refresh(organization);
			
		}
		catch(DataAccessException e) {
			// Critical errors : database unreachable, etc.
			logger.error("Exception - DataAccessException occurs : "+e.getMessage()
					+" on complete checkLogin().");
		}
    }
    
    public void delOrganizationsHoneypotsId(int organizationId, int honeypotsId){
		if (0 == organizationId || 0 == honeypotsId) {
			throw new IllegalArgumentException("An organizationId and a honeypotsId have to be specified");
		}	
		try {
			logger.debug("organizationId: " + organizationId + "honeypotsId: " + honeypotsId);
			Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
			Organizations organization = (Organizations) session.load(Organizations.class, new Integer(organizationId));
			
			//We add the HoneypotId to the honeypots list of our current Organization
			String listHoneypotsId = organization.getHoneypotsId();
			String[] tableHoneypotsId = listHoneypotsId.split("\\,");
			String newListHoneypotsId = null;
			for ( String s : tableHoneypotsId ){
				if ( newListHoneypotsId == null){
					if(s.compareTo(String.valueOf(honeypotsId)) != 0){
						newListHoneypotsId = s;
					}
				}
				else{
					if(s != String.valueOf(honeypotsId)){
						newListHoneypotsId.concat(","+s);
					}				
				}
			}
			logger.debug("listHoneypotsId after concat:" + newListHoneypotsId);
			organization.setHoneypotsId(newListHoneypotsId); 
			session.update(organization);
			session.flush();
			session.refresh(organization);
			
		}
		catch(DataAccessException e) {
			// Critical errors : database unreachable, etc.
			logger.error("Exception - DataAccessException occurs : "+e.getMessage()
					+" on complete checkLogin().");
		}
    }

}
